package network

import (
	"fmt"
	"net"
	"strconv"
	"time"
	"zcommom/commom"
)

//得到linux
//得到当前网速，单位Kb/s,recv上传速度，send出口带宽
func GetNetDev(ethx string) (recvs string, sends string) {
	recv1, send1 := getNetCmd(ethx)
	time.Sleep(time.Second * 1)
	recv2, send2 := getNetCmd(ethx)
	//下载素材
	send := send2 - send1
	if send1 > send1 {
		send = send1 - send2
	}
	//上传素材
	recv := recv1 - recv2
	if recv2 > recv1 {
		recv = recv2 - recv1
	}
	recv = recv / 1024
	recvs = strconv.FormatInt(recv, 10)
	send = send / 1024
	sends = strconv.FormatInt(send, 10)
	return recvs, sends
}

func getNetCmd(dev string) (rx, tx int64) {
	var recv, send string
	re := `cat /proc/net/dev | grep ` + dev + ` | tr : " " | awk '{print $2}'`
	recv, _ = commom.RunCommand(re)
	if recv != "" {
		rx, _ = strconv.ParseInt(recv, 10, 64)
	}
	rs := `cat /proc/net/dev | grep ` + dev + ` | tr : " " | awk '{print $10}'`
	send, _ = commom.RunCommand(rs)
	if send != "" {
		tx, _ = strconv.ParseInt(send, 10, 64)
	}

	return rx, tx
}

//检查端口是否可以使用,tcp
func CheckPort(ip string, port string) string {
	results := "error"
	address := net.JoinHostPort(ip, port)
	// 3 秒超时
	conn1, err := net.DialTimeout("tcp", address, 3*time.Second)
	if err != nil {
		results = "error"
	} else {
		if conn1 != nil {
			results = "success"
			conn1.Close()
		} else {
			results = "error"
		}
	}
	return results
}

//得到MAC地址
func getMacAddrs() (macAddrs []string) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Printf("fail to get net interfaces: %v", err)
		return macAddrs
	}

	for _, netInterface := range netInterfaces {
		macAddr := netInterface.HardwareAddr.String()
		if len(macAddr) == 0 {
			continue
		}

		macAddrs = append(macAddrs, macAddr)
	}
	return macAddrs
}

//得到IP的值列表
func getIPs() (ips []string) {
	interfaceAddr, err := net.InterfaceAddrs()
	if err != nil {
		return ips
	}
	for _, address := range interfaceAddr {
		ipNet, isValidIpNet := address.(*net.IPNet)
		if isValidIpNet && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				ips = append(ips, ipNet.IP.String())
			}
		}
	}
	return ips
}
